/*******************************************************************/
/* @ All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.        */
/*                                                                 */
/*  NAME      = frshm_exit_main.c                                  */
/*  NOTE      = 初始化共享内存                                     */
/*  DATE      = 2016/02/03 by guojq                                */
/*******************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

#include "frlog.h"
#include "frshm_pool.h"
#include "frsem.h"
#include "frdssl.h"
#include "frshm_stat.h"

#define APM_CFG_FILENAME_ZLOG             "../conf/zlog.conf"       /* zlog配置文件 */

static void __usage(char *p_pgname)
{
    printf("Usage: %s [OPTIONS]\n", p_pgname);
    printf("param info\n");
    printf("\t-p 共享内存的IPC文件    (default:../temp/shm_ssl_file)\n");
    printf("\t-s 进程锁的IPC文件      (default:../temp/sem_ssl_file)\n");
    printf("\t-h help.\n");
}

int main(int argc, char** argv)
{
    int i_shm_id = 0, i_sem_id = 0;
    char *p_shm_file = SHM_FILE;
    char *p_sem_file = SEM_FILE;
    int i_flag = 0;
    
    while ((i_flag = getopt(argc,argv,"p:s:h")) != -1)
    {
        switch (i_flag)
        {
            //共享内存的IPC文件
            case 'p':
                p_shm_file = optarg;
                break;
            //进程锁的IPC文件
            case 's':
                p_sem_file = optarg;
                break;
            case 'h':
                __usage(argv[0]);
                return 0;
            default:
                break;
        }
    }
    if (frlog_open(APM_CFG_FILENAME_ZLOG, "dssl"))
    {
        printf("log_open failed\n");
        return 1;
    }
    
    i_shm_id = frshm_pool_get(p_shm_file);
    if (i_shm_id < 0)
    {
        printf("[%s] get share memory failed\n", p_shm_file);
        i_sem_id = frsem_get(p_sem_file);
        if (i_sem_id < 0)
        {
            printf("[%s] get semaphore failed\n", p_sem_file);
            frlog_close();
            return 0;
        }
        frsem_free(i_sem_id);
        frlog_close();
        return 0;
    }
    frshm_pool_free(i_shm_id);
    
    i_sem_id = frsem_get(p_sem_file);
    if (i_sem_id < 0)
    {
        printf("[%s] get semaphore failed\n", p_sem_file);
        frlog_close();
        return 0;
    }
    frsem_free(i_sem_id);
    
    //关闭共享内存统计
    frshm_stat_exit();
    frlog_close();
    
    return 1;
}
